package com.hermit.server.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageAutoDialect;
import com.hermit.server.domain.RoleUser;
import com.hermit.server.domain.RoleUserExample;
import com.hermit.server.dto.RoleUserDto;
import com.hermit.server.dto.PageDto;
import com.hermit.server.mapper.RoleUserMapper;
import com.hermit.server.util.CopyUtil;
import com.hermit.server.util.UUidUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@Service
public class RoleUserService {
    @Resource
    private RoleUserMapper roleUserMapper;

    /** 查询*/
    public void list(PageDto pageDto){
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());
        RoleUserExample roleUserExample = new RoleUserExample();
        /** 根据sort来排序*/

        List<RoleUser> roleUserList = roleUserMapper.selectByExample(roleUserExample);
        //查询数据
        PageInfo<RoleUser> pageInfo = new PageInfo<>(roleUserList);
        //设置已查询条数
        pageDto.setTotal(pageInfo.getTotal());

        List<RoleUserDto> roleUserDtoList = new ArrayList<RoleUserDto>();
        for (int i = 0; i < roleUserList.size(); i++) {
            RoleUser roleUser = roleUserList.get(i);
            RoleUserDto roleUserDto = new RoleUserDto();
            BeanUtils.copyProperties(roleUser,roleUserDto);
            roleUserDtoList.add(roleUserDto);
        }
        //设置最终查询结果
        pageDto.setList(roleUserDtoList);
        //return pageDto;  pageDto是从前端传递来的，按道理应该有返回值，此处传入对象==返回对象，属于原地返回（杨凡专用名词）
    }
    /** 保存*/
    public void save(RoleUserDto roleUserDto){
        RoleUser roleUser = CopyUtil.copy(roleUserDto,RoleUser.class);
        if(StringUtils.isEmpty(roleUserDto.getId())){
            this.insert(roleUser);
        }else{
            this.update(roleUser);
        }

    }
    /**新增 */
    private void insert(RoleUser roleUser){
        roleUser.setId(UUidUtil.getShortUuid());
        roleUserMapper.insert(roleUser);
    }
    /**修改更新 */
    private void update(RoleUser roleUser){
        roleUserMapper.updateByPrimaryKey(roleUser);
    }
    /**删除 */
    public void delete(String id){
        roleUserMapper.deleteByPrimaryKey(id);
    }
}